<?php
namespace Modules\Home\Controllers;

use Modules\Home\Models\UserModel;

use Modules\Home\Services\UserWalletService;
use Modules\Home\Services\UserWalletGoodsLogService;

class GoodsController extends ControllerBase {
  public function initialize() {
    $this -> _checkLogin();
  }

  public function handleTransferAction() {
    if(!$this -> security -> checkToken()) {
      return $this -> _returnScript('已提交成功，请勿重复提交!');
    }

    $post = $this -> request -> getPost();

    // 验证
    $goodsValidationCreate = (new \Modules\Home\Validations\GoodsValidation()) -> transfer($post);
    if($goodsValidationCreate['code'] != 0) {
      return $this -> _returnScript($goodsValidationCreate['message']);
    }

    $sessionGetUser = $this -> session -> get('user');

    $findFirstTransferUser = UserModel::findFirst('user_id = "' . $sessionGetUser['user_id'] . '"');
    if(!$this -> security -> checkHash($post['safe_password'], $findFirstTransferUser -> safe_password)) {
      return $this -> _returnScript('安全密码错误!');
    }

    $findFirstBeTransferUser = UserModel::findFirst('user_code = "' . $post['user_code'] . '"');
    if(!$findFirstBeTransferUser) {
      return $this -> _returnScript('转账的用户不存在!');
    }

    $userWalletService = new UserWalletService();
    $transferUserWallet = $userWalletService -> getOne($sessionGetUser['user_id']);
    if($post['num'] > $transferUserWallet['data']['user_wallet'] -> goods) {
      return $this -> _returnScript('货的余额不足!');
    }

    $currentTime = time();
    $transaction = (new \Phalcon\Mvc\Model\Transaction\Manager()) -> get();

    $transferUserWalletGoodsLogData = [
      'user_id' => $sessionGetUser['user_id'],
      'from_user_id' => $findFirstBeTransferUser -> user_id,
      'type' => 32,
      'active' => 0,
      'is_draw' => 1,
      'draw_time' => $currentTime,
      'create_time' => $currentTime,
      'goods' => $post['num'],
      'goods_new' => $transferUserWallet['data']['user_wallet'] -> goods - $post['num'],
      'goods_old' => $transferUserWallet['data']['user_wallet'] -> goods,
      'poundage' => 0
    ];
    $transferUserWallet['data']['user_wallet'] -> goods -= $post['num'];

    $beTransferUserWallet = $userWalletService -> getOne($findFirstBeTransferUser -> user_id);
    $beTransferUserWalletGoodsLogData = [
      'user_id' => $findFirstBeTransferUser -> user_id,
      'from_user_id' => $sessionGetUser['user_id'],
      'type' => 31,
      'active' => 1,
      'is_draw' => 1,
      'draw_time' => $currentTime,
      'create_time' => $currentTime,
      'goods' => $post['num'],
      'goods_new' => $beTransferUserWallet['data']['user_wallet'] -> goods + $post['num'],
      'goods_old' => $beTransferUserWallet['data']['user_wallet'] -> goods,
      'poundage' => 0
    ];
    $beTransferUserWallet['data']['user_wallet'] -> goods += $post['num'];
    $userWalletGoodsLogService = new UserWalletGoodsLogService();

    try {
      $transferUserWallet['data']['user_wallet'] -> setTransaction($transaction);
      if(!$transferUserWallet['data']['user_wallet'] -> save()) {
        foreach($transferUserWallet['data']['user_wallet'] -> getMessages() as $message) {
          $transaction -> rollback($message -> getMessage());
        }
      }

      $beTransferUserWallet['data']['user_wallet'] -> setTransaction($transaction);
      if(!$beTransferUserWallet['data']['user_wallet'] -> save()) {
        foreach($beTransferUserWallet['data']['user_wallet'] -> getMessages() as $message) {
          $transaction -> rollback($message -> getMessage());
        }
      }

      $createTransferUserWalletGoodsLog = $userWalletGoodsLogService -> create($transferUserWalletGoodsLogData);
      if($createTransferUserWalletGoodsLog['code'] != 0) {
        throw new \Exception($createBeTransferUserWalletGoodsLog['message']);
      }

      $createBeTransferUserWalletGoodsLog = $userWalletGoodsLogService -> create($beTransferUserWalletGoodsLogData);
      if($createBeTransferUserWalletGoodsLog['code'] != 0) {
        throw new \Exception($createBeTransferUserWalletGoodsLog['message']);
      }

      $transaction -> commit();
    } catch(\Exception $e) {
      return $this -> _returnScript('转账失败: ' . $e -> getMessage());
    }

    return $this -> _returnScript('转账成功', '/finance');
  } 
}
